import 'package:bloc_pattern/bloc_pattern.dart';
import 'package:flutter/material.dart';
import 'package:flutter_food_delivery_app_ui/model/food_item.dart';

import 'bloc/cart_list_bloc.dart';
import 'cart.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  //https://www.youtube.com/watch?v=wWH66F9y63U
  //This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      blocs: [Bloc((i) => CartListBlocController())],
      child: MaterialApp(
        title: 'Food Delivery App UI with Functionality - Flutter',
        theme: ThemeData(
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
        ),
        home: Home(),
        //MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Container(
        child: ListView(
          children: <Widget>[
            FirstHalf(),
            SizedBox(
              height: 45,
            ),
            for (var foodItem in foodItemList.foodItems)
              ItemContainer(foodItem: foodItem)
          ],
        ),
      )),
    );
  }
}

class ItemContainer extends StatelessWidget {
  final FoodItem foodItem;
  ItemContainer({this.foodItem});

  final CartListBlocController cartListBlocController =
      BlocProvider.getBloc<CartListBlocController>();


  void addToCart(FoodItem foodItem){
    cartListBlocController.addToList(foodItem);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        addToCart(foodItem);
        final snackbar = SnackBar(
          content: Text('${foodItem.title} added!'),
          duration: Duration(milliseconds: 550),
        );
        Scaffold.of(context).showSnackBar(snackbar);
      },
      child: Items(
          hotel: foodItem.hotel,
          itemName: foodItem.title,
          itemPrice: foodItem.price,
          imgUrl: foodItem.imgUrl,
          leftAligned: (foodItem.id % 2 == 0) ? true : false),
    );
  }
}

class Items extends StatelessWidget {
  final String hotel;
  final String itemName;
  final double itemPrice;
  final String imgUrl;
  final bool leftAligned;

  Items(
      {this.hotel,
      this.itemName,
      this.itemPrice,
      this.imgUrl,
      this.leftAligned});

  @override
  Widget build(BuildContext context) {
    double containerPadding = 45;
    double containerBorderRadius = 10;

    return Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(
              left: leftAligned ? 0 : containerPadding,
              right: leftAligned ? containerPadding : 0),
          child: Column(
            children: <Widget>[
              Container(
                  width: double.infinity,
                  height: 200,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.horizontal(
                        left: leftAligned
                            ? Radius.circular(0)
                            : Radius.circular(containerBorderRadius),
                        right: leftAligned
                            ? Radius.circular(containerBorderRadius)
                            : Radius.circular(0)),
                    child: Image.network(this.imgUrl,
                    fit: BoxFit.fill,)
                  )),
              SizedBox(height: 20,),
              Container(
                padding: EdgeInsets.only(
                  left: leftAligned?20:0,
                  right: leftAligned?0:20
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(
                            itemName,
                            style: TextStyle(
                              fontWeight: FontWeight.w700,
                              fontSize: 18,
                            ),
                          ),
                        ),
                        Text("\$$itemPrice",
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                        ),)
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(height: 10,),
              Align(
                alignment: Alignment.centerLeft,
                child: RichText(
                  text: TextSpan(
                    style: TextStyle(
                      color:Colors.black45,
                      fontSize: 15
                    ),
                    children: [
                      TextSpan(text: "by "),
                      TextSpan(text:  hotel,
                      style: TextStyle(
                        fontWeight: FontWeight.w500
                      ))
                    ]
                  ),
                ),
              ),
              SizedBox(height: containerPadding,)
            ],
          ),
        )
      ],
    );
  }
}

class FirstHalf extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(35, 25, 0, 0),
      child: Column(
        children: <Widget>[
          CustomAppBar(),
          SizedBox(
            height: 30,
          ),
          title(),
          SizedBox(
            height: 30,
          ),
          searchBar(),
          SizedBox(
            height: 30,
          ),
          categories()
        ],
      ),
    );
  }

  Widget title() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(
          width: 45,
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Food',
                style: TextStyle(
                    color: Colors.red,
                    fontWeight: FontWeight.w700,
                    fontSize: 30)),
            Text(
              'Delivery',
              style: TextStyle(fontWeight: FontWeight.w300, fontSize: 30),
            )
          ],
        )
      ],
    );
  }

  Widget searchBar() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Icon(Icons.search, color: Colors.black45),
        SizedBox(
          width: 20,
        ),
        Expanded(
          child: TextField(
            decoration: InputDecoration(
                hintText: '查找......',
                contentPadding: const EdgeInsets.symmetric(vertical: 10),
                hintStyle: TextStyle(color: Colors.black87)),
          ),
        )
      ],
    );
  }

  Widget categories() {
    return Container(
      height: 185,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          CategoryListItem(
              categoryIcon: Icons.local_pizza,
              categoryName: 'Pizza',
              availability: 12,
              selected: true),
          CategoryListItem(
              categoryIcon: Icons.free_breakfast,
              categoryName: 'Hanbager',
              availability: 12,
              selected: false),
          CategoryListItem(
              categoryIcon: Icons.account_circle,
              categoryName: 'Bread',
              availability: 12,
              selected: false),
          CategoryListItem(
              categoryIcon: Icons.bug_report,
              categoryName: 'Burgers',
              availability: 12,
              selected: false),
          CategoryListItem(
              categoryIcon: Icons.bug_report,
              categoryName: 'Roll',
              availability: 12,
              selected: false),
          CategoryListItem(
              categoryIcon: Icons.bug_report,
              categoryName: 'Burgers',
              availability: 12,
              selected: false)
        ],
      ),
    );
  }
}

class CategoryListItem extends StatelessWidget {
  final IconData categoryIcon;
  final String categoryName;
  final int availability;
  final bool selected;

  CategoryListItem(
      {this.categoryIcon, this.categoryName, this.availability, this.selected});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(right: 20),
      padding: EdgeInsets.fromLTRB(10, 10, 10, 20),
      decoration: BoxDecoration(
          border: Border.all(
              color: selected ? Colors.transparent : Colors.grey[200],
              width: 1.5),
          boxShadow: [
            BoxShadow(
                color: Colors.grey[100],
                blurRadius: 15,
                offset: Offset(25, 0),
                spreadRadius: 5)
          ],
          borderRadius: BorderRadius.circular(50),
          color: selected ? Color(0xfffeb324) : Colors.white),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                    color: selected ? Colors.transparent : Colors.grey,
                    width: 1.5)),
            child: Icon(categoryIcon, size: 30),
          ),
          SizedBox(
            height: 10,
          ),
          Text(
            categoryName,
            style: TextStyle(fontWeight: FontWeight.w700, color: Colors.black),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(0, 0, 0, 10),
            width: 1.5,
            height: 15,
            color: Colors.black26,
          ),
          Text(
            availability.toString(),
            style: TextStyle(fontWeight: FontWeight.w600),
          )
        ],
      ),
    );
  }
}

class CustomAppBar extends StatelessWidget {
  final CartListBlocController cartListBlocController =
      BlocProvider.getBloc<CartListBlocController>();

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Icon(Icons.menu),
          StreamBuilder(
            stream: cartListBlocController.outListStream,
            builder:(context,snapshot){
              List<FoodItem> foodsItems = snapshot.data;
              int length = foodsItems!=null? foodsItems.length:0;
              int itemCount = 0;
              if(foodsItems != null){
                for(var i in foodsItems){
                  itemCount += i.quantity;
                }
              }

              return  GestureDetector(
                onTap: () {
                  //判断是否>0 true跳转到Cart中，否则不作任何动作
                  if(length>0){
                    Navigator.push(context, MaterialPageRoute(builder:
                    (context)=>Cart()));
                  }
                },
                child: Container(
                  margin: const EdgeInsets.only(right: 30),
                  child: Text(itemCount.toString()),//length.toString()),
                  padding: const EdgeInsets.all(15),
                  decoration: BoxDecoration(
                      color: Colors.yellow[800],
                      borderRadius: BorderRadius.circular(50)),
                ),
              );
            },
          )
        ],
      ),
    );
  }
}

